/**
 *  主题切换模块
 *  @module utils/theme
 */

import {get, save, LOCAL} from './storage'

let setting = {
  path: '/static/css/',
  cacheKey: '__THEME__',
  theme: 'default'
}

let head = null
let link = null

/**
 * 创建 link 标签
 * @private
 * @return {HTMLElement}
 */
function createLink() {
  if (link) return link
  link = window.document.createElement('link')
  link.type = 'text/css'
  link.rel = 'stylesheet'
  head = head || window.document.getElementsByTagName('head')[0]
  head.appendChild(link)
  return link
}

/**
 * 加载主题
 * @private
 * @param {string} name 主题名称，不含后缀名
 */
function load(name) {
  const el = createLink()
  el.href = `${setting.path}theme-${name}.css`
  save(setting.cacheKey, name, LOCAL)
}

/**
 * 初始化主题
 * @param {Object} [config] 主题配置
 * @param {String} [config.path='/static/css/'] 主题样式文件路径
 * @param {String} [config.cacheKey='__THEME__'] 缓存key
 * @param {String} [config.theme='default'] 默认主题名称
 */
export default function (config) {
  Object.assign(setting, config || {})
  let theme = get(setting.cacheKey, LOCAL) || setting.theme
  load(theme)
}

/**
 * 更换主题
 * @param {string} name 主题名称，不含后缀名
 */
export function change(name) {
  load(name)
}
